import React, { useMemo, useState, useRef, useEffect, useCallback } from 'react'
import { observer, inject } from 'mobx-react'
import { find } from 'lodash'
import { toJS } from 'mobx'

import recordTime from '../../../store/record-time'
import video from '../../../store/video'
import Progress from '../../common/progress'
import './playback-progress.scss'
import useSubs from '../../../hooks/useSubs'
import common from '../../../store/common'

const customStyle = {
  bar: {
    background: '#222222',
  },
}

const PlaybackProgress = () => {
  const { videoType, curScreenId } = video
  const { event$ } = common

  const [progressLen, setProgressLen] = useState(0)
  const [isRecord, setIsRecord] = useState(videoType !== 'live')
  const [pct, setPct] = useState(0)
  const [timeArray] = useState(toJS(video.screenArr))

  const ref = useRef()
  const progressRef = useCallback((val) => {
    setPct(val?.pct ?? 0)
  })

  useEffect(() => {
    changeTime(pct)
  }, [pct])

  // 聚焦分屏，根据分屏对应的时间信息调整进度条
  useEffect(() => {
    const time = recordTime.getTimeById(curScreenId)
    if (time) {
      const { clientWidth } = ref.current
      const { duration, currentTime } = time
      setProgressLen(clientWidth * (currentTime / duration))
    } else {
      setProgressLen(0)
    }
  }, [video.curScreenId])

  useMemo(() => {
    videoType === 'live' ? setIsRecord(false) : setIsRecord(true)
  }, [videoType])

  useSubs(({ action, val }) => {
    if (action === 'setProgressLen') {
      const { clientWidth } = ref.current
      setProgressLen(clientWidth * val)
    }
  })

  function changeTime(pct) {
    if (isRecord) {
      event$.emit({ action: 'changeRecordTime', val: { id: curScreenId, pct } })
    } else {
      const time = find(timeArray, ['id', curScreenId])
      if (time) {
        const { start, end } = time
        const val = end.diff(start, 's') * pct
        const now = start.add(val, 's')
        recordTime.setTimeArray(curScreenId, 'now', now)
        event$.emit({ action: 'changeLiveTime', val: { id: curScreenId, time } })
      }
    }
  }

  return (
    <div ref={ref} className="playbackBar" style={{ display: isRecord ? 'block' : 'none' }}>
      <Progress ref={progressRef} height={7} customStyle={customStyle} progressLen={progressLen} />
    </div>
  )
}

export default inject('store')(observer(PlaybackProgress))
